const fs = require('fs');
const path = require('path');
const { pool } = require('../../db/index');
const Router = require('koa-router');
const router = new Router();
const formidable = require('formidable');
const moment = require('moment')

// 处理图片上传的路由
router.post('/api/friendcircle/publish', async (ctx) => {
    const files = ctx.request.files.images;
    const user_id = 1;
    const { title, content } = ctx.request.body;
    const filePaths = [];

    // 确保 imgs 文件夹存在
    const imgsDir = path.join(__dirname, '../../imgs/userPosts'); // 根路径的 imgs 文件夹
    if (!fs.existsSync(imgsDir)) {
        fs.mkdirSync(imgsDir, { recursive: true });
    }

    // 处理上传的文件
    if (Array.isArray(files)) {
        for (const file of files) {
            const fileName = path.basename(file.filepath); // 获取文件名
            const newFilePath = path.join(imgsDir, fileName); // 新文件路径
            fs.renameSync(file.filepath, newFilePath); // 将文件移动到 imgs 文件夹
            filePaths.push(fileName); // 存储相对路径
        }
    } else if (files) {
        const fileName = path.basename(files.filepath); // 获取文件名
        const newFilePath = path.join(imgsDir, fileName); // 新文件路径
        fs.renameSync(files.filepath, newFilePath); // 将文件移动到 imgs 文件夹
        filePaths.push(fileName); // 存储相对路径
    }

    const imagesJson = JSON.stringify(filePaths);
    const created_at = moment().format('YYYY-MM-DD HH:mm:ss');

    const connection = await pool.getConnection();
    try {
        await connection.execute(
            'INSERT INTO posts (user_id, title, content, created_at, images) VALUES (?,?,?,?,?)',
            [user_id, title, content, created_at, imagesJson]
        );
    } finally {
        connection.release();
    }

    ctx.body = {
        message: '图片上传成功',
        code: 200,
    };
});

// 获取帖子列表接口
router.get('/api/friendcircle/posts', async (ctx) => {
    try {
        // 获取页码和每页数量
        const page = parseInt(ctx.query.page) || 1;
        const pageSize = parseInt(ctx.query.pageSize) || 10;

        // 计算偏移量
        const offset = (page - 1) * pageSize;

        console.log('page', page, 'pageSize', pageSize);

        // 查询总记录数
        const [totalResult] = await pool.execute('SELECT COUNT(*) as total FROM posts');
        const total = totalResult[0].total;

        // 添加 ORDER BY 子句按 created_at 字段降序排序
        const sql = `SELECT posts.id, users.username, users.avatar, posts.title, posts.content, posts.images, posts.created_at 
                     FROM posts 
                     JOIN users ON posts.user_id = users.id 
                     ORDER BY posts.created_at DESC 
                     LIMIT ${offset}, ${pageSize}`;
        console.log('sql', sql);
        const [rows] = await pool.execute(sql);
        console.log('rows', rows);
        const posts = rows.map(post => {
            post.images = JSON.parse(post.images);
            post.images = post.images.map(item => `${module.exports.serverUrl}/imgs/userPosts/${item}`);
            return post;
        });
        console.log('posts', posts);
        ctx.body = {
            success: true,
            posts,
            total, // 返回总记录数
            code: 200
        };
    } catch (error) {
        console.error('获取帖子列表出错:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '获取帖子列表失败，请稍后重试'
        };
    }
});

module.exports = router;